<template>
  <input type="text" style="display: none;" id="clipboard" value="" />
  <div class="hello">
    <h1>{{ msg }}</h1>
    <div>
      <h3>演示版本==>https://api.testnet.solana.com | programId==>9WwPHyhq2EL3bmEGFoXvBdZHkzxh8c1XPp7CGPK6SqrY</h3><br>
      <button @click="conn">1、connect-wallet</button>
    </div>
    <div>
      <h5>payer：{{ wallet? wallet.publicKey.toBase58() : "" }}</h5>
    </div>
    <div>
      <button @click="sys_recharge">2、recharge 10 SOL</button>&nbsp;&nbsp;&nbsp;&nbsp;
    </div>
    <div>
      <h5>recharge sign：<a :href="`https://explorer.solana.com/tx/${rechargesign}?cluster=testnet`" target="_blank">{{
        rechargesign
      }}</a></h5>
    </div>
    <div>
      <button @click="hash_bet">3、bet 2 SOL</button>&nbsp;&nbsp;&nbsp;&nbsp;
    </div>
    <div>
      <h5>bet sign：<a :href="`https://explorer.solana.com/tx/${betsign}?cluster=testnet`" target="_blank">{{
        betsign
      }}</a></h5>
    </div>
    <div>
      <p>任何人都可以给奖池充值，但只有初始化奖池人(第一个充值的人)能够从中提现！！！</p>
      <button @click="sys_withdrawal">4、withdrawal 5 SOL</button>&nbsp;&nbsp;&nbsp;&nbsp;
    </div>
    <div>
      <h5>withdrawal sign：<a :href="`https://explorer.solana.com/tx/${withdrawalsign}?cluster=testnet`"
          target="_blank">{{ withdrawalsign }}</a></h5>
      <h5 style="color:red">{{ errorMsg }}</h5>
    </div>

  </div>
</template>

<script>
import { LAMPORTS_PER_SOL, SystemProgram, Transaction, TransactionInstruction, Connection, PublicKey, SYSVAR_SLOT_HASHES_PUBKEY } from "@solana/web3.js";
import BN from "bn.js";
import { sha256 } from "js-sha256";
window.Buffer = window.Buffer || require('buffer').Buffer;

export default {
  name: 'HelloWorld',
  props: {
    msg: String
  },
  data() {
    return {
      programId: new PublicKey("9WwPHyhq2EL3bmEGFoXvBdZHkzxh8c1XPp7CGPK6SqrY"),
      connection: undefined,
      wallet: undefined,
      rechargesign: "",
      betsign: "",
      withdrawalsign: "",
      errorMsg: "",
    }
  },
  async created() {

  },
  methods: {
    async getProvider() {
      if ("solana" in window) {
        await window.solana.connect();
        const provider = window.solana;
        if (provider.isPhantom) {
          return provider;
        }
      } else {
        document.write('Install https://www.phantom.app/');
      }
    },
    async conn() {
      const provider = await this.getProvider();
      const network = "https://api.testnet.solana.com";
      // const network = "http://localhost:8899";
      const connection = new Connection(network);
      this.connection = connection;
      this.wallet = provider;
    },
    async sys_recharge() {
      const provider = await this.getProvider();
      const connection = this.connection;
      const [bet_pool] = await PublicKey.findProgramAddress(
        [Buffer.from("bet_pool_seed", "utf8")],
        this.programId
      );

      const instructionBuffer = Buffer.concat([
        Buffer.from(sha256.digest("global:sys_recharge")).slice(0, 8),
        Buffer.from(new Uint8Array(new BN(10 * LAMPORTS_PER_SOL).toArray("le", 8)))
      ]);
      const transaction = new Transaction().add(
        new TransactionInstruction({
          keys: [
            { pubkey: this.wallet.publicKey, isSigner: true, isWritable: true },
            { pubkey: bet_pool, isSigner: false, isWritable: true },
            { pubkey: SystemProgram.programId, isSigner: false, isWritable: false }
          ],
          data: instructionBuffer,
          programId: this.programId,
        })
      );
      transaction.recentBlockhash = (await connection.getLatestBlockhash("max")).blockhash;
      transaction.feePayer = provider.publicKey;
      const { signature } = await provider.signAndSendTransaction(transaction);
      await connection.getSignatureStatus(signature);
      this.rechargesign = signature;
    },
    async hash_bet() {
      const provider = await this.getProvider();
      const connection = this.connection;
      const [bet_pool] = await PublicKey.findProgramAddress(
        [Buffer.from("bet_pool_seed", "utf8")],
        this.programId
      );

      const instructionBuffer = Buffer.concat([
        Buffer.from(sha256.digest("global:hash_bet")).slice(0, 8),
        Buffer.from(new Uint8Array(new BN(2 * LAMPORTS_PER_SOL).toArray("le", 8)))
      ]);
      const transaction = new Transaction().add(
        new TransactionInstruction({
          keys: [
            { pubkey: this.wallet.publicKey, isSigner: true, isWritable: true },
            { pubkey: bet_pool, isSigner: false, isWritable: true },
            { pubkey: SYSVAR_SLOT_HASHES_PUBKEY, isSigner: false, isWritable: true },
            { pubkey: SystemProgram.programId, isSigner: false, isWritable: false }
          ],
          data: instructionBuffer,
          programId: this.programId,
        })
      );
      transaction.recentBlockhash = (await connection.getLatestBlockhash("max")).blockhash;
      transaction.feePayer = provider.publicKey;
      const { signature } = await provider.signAndSendTransaction(transaction);
      await connection.getSignatureStatus(signature);
      this.betsign = signature;
    },
    async sys_withdrawal() {
      const provider = await this.getProvider();
      const connection = this.connection;
      const [bet_pool] = await PublicKey.findProgramAddress(
        [Buffer.from("bet_pool_seed", "utf8")],
        this.programId
      );

      const instructionBuffer = Buffer.concat([
        Buffer.from(sha256.digest("global:sys_withdrawal")).slice(0, 8),
        Buffer.from(new Uint8Array(new BN(5 * LAMPORTS_PER_SOL).toArray("le", 8)))
      ]);
      const transaction = new Transaction().add(
        new TransactionInstruction({
          keys: [
            { pubkey: this.wallet.publicKey, isSigner: true, isWritable: true },
            { pubkey: bet_pool, isSigner: false, isWritable: true },
            { pubkey: SystemProgram.programId, isSigner: false, isWritable: false }
          ],
          data: instructionBuffer,
          programId: this.programId,
        })
      );
      transaction.recentBlockhash = (await connection.getLatestBlockhash("max")).blockhash;
      transaction.feePayer = provider.publicKey;
      try {
        const { signature } = await provider.signAndSendTransaction(transaction);
        await connection.getSignatureStatus(signature);
        this.withdrawalsign = signature;
      } catch (error) {
        this.errorMsg = "非管理员不能提现！";
      }

    },
  }
}
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>
h3 {
  margin: 40px 0 0;
}

ul {
  list-style-type: none;
  padding: 0;
}

li {
  display: inline-block;
  margin: 0 10px;
}

a {
  color: #42b983;
}
</style>
